package com.cms.manage.service.impl;

import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.cms.manage.common.ConmonConfig;
import com.cms.manage.common.SysCode;
import com.cms.manage.dao.CmsStoreListMapper;
import com.cms.manage.dao.CmsStoreLogMapper;
import com.cms.manage.dao.CmsUserMapper;
import com.cms.manage.model.CmsClassfy;
import com.cms.manage.model.CmsStore;
import com.cms.manage.model.CmsStoreList;
import com.cms.manage.model.CmsStoreLog;
import com.cms.manage.model.CmsUser;
import com.cms.manage.service.StoreLogService;
import com.cms.manage.service.StoreService;
import com.cms.manage.util.MapUtil;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;

import tk.mybatis.mapper.entity.Example;
import tk.mybatis.mapper.entity.Example.Criteria;

/**
 * Created by sgy on 2017/4/7.
 */
@Service
public class StoreLogServiceImpl extends BaseService<CmsStoreLog> implements StoreLogService {

	
	@Autowired 
	private CmsStoreLogMapper cmsStoreLogMapper;

	@Autowired 
	private CmsStoreListMapper cmsStoreListMapper;
	
	@Autowired 
	private CmsUserMapper cmsUserMapper;
	
	
	/**
	 * Created by sgy on 2020/6/7.
	 * 
	 * 查询入库列表
	 * 参数，非空  启示页pageNum:1  分页大小 pageSize:6
	 * operate 0:出库 1:入库
	 */
	@Override
	public Map<String, Object> searchStoreOutAndIn(Map<String, String> data) {
		Map<String, Object> result = ConmonConfig.getResultMap();	
		StringBuffer message = new StringBuffer(); 
		if(!(result.get("code")==SysCode.error)){//必录字段都存在
			//查询所有入库单
		    Example example = new Example(CmsStoreLog.class);
			example.setOrderByClause("id desc");
			Criteria criteria=example.createCriteria();
			 Map<String,Object> param = new HashMap<>();	
			 if(StringUtils.isNotBlank(MapUtil.getString(data, "operate"))){//名字筛选
				 param.put("operate", MapUtil.getString(data, "operate"));
				 criteria.andEqualTo(param);
			 }
			 if(StringUtils.isNotBlank(MapUtil.getString(data, "name"))){//名字筛选
				 criteria.andLike("goodName", "%" + MapUtil.getString(data, "name") + "%"); 
			 }		
			PageHelper.startPage(MapUtil.getInt(data, "pageNum"), MapUtil.getInt(data, "pageSize"));
			List<CmsStoreLog>  rs =cmsStoreLogMapper.selectByExample(example);
		    //返回分页信息
		    PageInfo<CmsStoreLog> pageInfo = new PageInfo<>(rs);
		    result.put("data", pageInfo);
		}
		result.put("message", message.toString());	
		return result;
	}
	/**
	 * Created by sgy on 2020/6/7.
	 * 
	 * 新增或编辑入库/出库单
	 * 参数，非空 operate 0:出库 1:入库  进货单id:relateId  数量:number
	 *       主键id 有id更新，无id插入
	 */
	@Override
	public Map<String, Object> addStoreOutAndInList(Map<String, String> data) {
		

		Map<String, Object> result = ConmonConfig.getResultMap();	
		StringBuffer message = new StringBuffer(); 
		//校验非空
		if(StringUtils.isBlank(data.get("operate"))){
			result.put("code",SysCode.error);
			message.append("操作标识不能为空! ");
		}
		if(StringUtils.isBlank(data.get("relateId"))){
			result.put("code",SysCode.error);
			message.append("商品不能为空! ");
		}
		if(MapUtil.getInt(data, "number")==null){
			result.put("code",SysCode.error);
			message.append("数量不能为空! ");
		}		
		if(StringUtils.isBlank(data.get("userTotalId"))){
			result.put("code",SysCode.error);
			message.append("提交人不能为空! ");
		}
		//获取最新的用户对象
		CmsUser cmsUser = cmsUserMapper.selectByPrimaryKey(MapUtil.getInt(data, "userTotalId"));			
		if(!(result.get("code")==SysCode.error)){//必录字段都存在
			CmsStoreList cmsStoreList = cmsStoreListMapper.selectByPrimaryKey(MapUtil.getInt(data, "relateId"));
			cmsStoreList.setCreateTime(new Date());
			cmsStoreList.setUpdateTime(new Date());
			cmsStoreList.setUserId(cmsUser.getId());
			cmsStoreList.setUserName(cmsUser.getName());				
			if (StringUtils.isNoneBlank(MapUtil.getString(data,"id"))) {//编辑入库单
				int id = MapUtil.getInt(data,"id");
				//查询寻原始数据是否存在
			    CmsStoreLog cmsStoreLog = cmsStoreLogMapper.selectByPrimaryKey(id);
				//获取到原始数量,如果库存没变更，则不插入库存日志
				if(cmsStoreLog!=null){
					boolean flag = true;
					int editNumber = cmsStoreLog.getEditNumber();//原editnumber
					int currentEditNumber = MapUtil.getInt(data, "number");
					if(editNumber==currentEditNumber){//如果相等则不操作
						flag=false;						
					}					
					if(flag){
						int number = cmsStoreList.getNumber();
						if(MapUtil.getInt(data, "operate")==0){//出库,原始-变更
							cmsStoreList.setNumber(number-(currentEditNumber-editNumber));
						}else if(MapUtil.getInt(data, "operate")==1){//入库,原始+变更
							cmsStoreList.setNumber(number+(currentEditNumber-editNumber));
						}
						int upt =cmsStoreListMapper.updateByPrimaryKey(cmsStoreList);//编辑后红冲库存			
						if(upt==0){
							result.put("code",SysCode.error);
							message.append("提交失败,网络异常 ");
						}else{
							//cmsStoreLog.setCreateTime(new Date());
							cmsStoreLog.setEditNumber(currentEditNumber);
							cmsStoreLog.setUserId(cmsUser.getId());
							cmsStoreLog.setUserName(cmsUser.getName());
							int upte = cmsStoreLogMapper.updateByPrimaryKey(cmsStoreLog);					
							if(upte==0){
								//回滚数据				
								result.put("code",SysCode.error);
								message.append("库存编辑日志插入异常 ：提货单号--"+cmsStoreList.getId());
							}
						}							
						}										
				}		
			}else{//插入提货单直接插入记录同时更新 入库id  进货端是 relateId						
				//判断标识0:出库 1:入库 
				//当前原库数量
				int number = cmsStoreList.getNumber();
				int editNumber= MapUtil.getInt(data, "number");
				if(MapUtil.getInt(data, "operate")==0){//出库,原始-变更
					cmsStoreList.setNumber(number-editNumber);
				}else if(MapUtil.getInt(data, "operate")==1){//入库,原始+变更
					cmsStoreList.setNumber(number+editNumber);
				}
				int upt =cmsStoreListMapper.updateByPrimaryKey(cmsStoreList);				
				if(upt==0){
					result.put("code",SysCode.error);
					message.append("提交失败,网络异常 ");
				}else{
					 //插入流程日志
					CmsStoreLog cmsStoreLog  = new CmsStoreLog();
					cmsStoreLog.setGoodName(cmsStoreList.getGoodName());
					cmsStoreLog.setCreateTime(new Date());
					cmsStoreLog.setNumber(number);//变更前数量
					cmsStoreLog.setEditNumber(editNumber);//变更数量
					cmsStoreLog.setOperate(MapUtil.getShort(data, "operate"));//操作标识
					cmsStoreLog.setRelateId(cmsStoreList.getId());//入库单ID
					cmsStoreLog.setUserId(cmsUser.getId());
					cmsStoreLog.setUserName(cmsUser.getName());
					//新增4个字段
					cmsStoreLog.setDate(cmsStoreList.getDate());
					cmsStoreLog.setRank(cmsStoreList.getRank());
					cmsStoreLog.setGoodSize(cmsStoreList.getGoodSize());
					cmsStoreLog.setBankName(cmsStoreList.getBankName());
					int logcont = cmsStoreLogMapper.insert(cmsStoreLog);
					if(logcont==0){
						//回滚数据				
						result.put("code",SysCode.error);
						message.append("日志插入异常 ：提货单号--"+cmsStoreList.getId());
					}
				}			
			}							   
		}		
		result.put("message", message.toString());			
		return result;
	
	}
	/**
	 * Created by sgy on 2020/6/7.
	 * 
	 * 删除入库/出库单
	 * 参数，非空 主键id operate:操作标识 0:出库1:入库  relateId:进货单ID userName userId
	  */	
	@Override
	public Map<String, Object> deleteStoreOutAndInList(Map<String, String> data) {	
		Map<String, Object> result = ConmonConfig.getResultMap();	
		StringBuffer message = new StringBuffer(); 
		//校验非空
		if(StringUtils.isBlank(data.get("operate"))){
			result.put("code",SysCode.error);
			message.append("操作标识不能为空! ");
		}
		if(StringUtils.isBlank(data.get("id"))){
			result.put("code",SysCode.error);
			message.append("操作数据不能为空 ");
		}
		if(StringUtils.isBlank(data.get("relateId"))){
			result.put("code",SysCode.error);
			message.append("操作数据不能为空 ");
		}
		if(StringUtils.isBlank(data.get("userTotalId"))){
			result.put("code",SysCode.error);
			message.append("提交人不能为空! ");
		}
		//获取最新的用户对象
		CmsUser cmsUser = cmsUserMapper.selectByPrimaryKey(MapUtil.getInt(data, "userTotalId"));
		//删除记录要进行回滚
		CmsStoreList cmsStoreList = cmsStoreListMapper.selectByPrimaryKey(MapUtil.getInt(data, "relateId"));
		cmsStoreList.setCreateTime(new Date());
		cmsStoreList.setUpdateTime(new Date());
		cmsStoreList.setUserId(cmsUser.getId());
		cmsStoreList.setUserName(cmsUser.getName());
		int id = MapUtil.getInt(data,"id");
		//查询寻原始数据是否存在
	    CmsStoreLog cmsStoreLog = cmsStoreLogMapper.selectByPrimaryKey(id);
	    if(cmsStoreLog!=null){
	    	int number = cmsStoreList.getNumber();//当前的库存
			int editNumber= cmsStoreLog.getEditNumber();
			if(MapUtil.getInt(data, "operate")==0){//出库,删除 原始+变更
				cmsStoreList.setNumber(number+editNumber);
			}else if(MapUtil.getInt(data, "operate")==1){//入库,原始-变更
				cmsStoreList.setNumber(number-editNumber);
			}			
			int upt =cmsStoreListMapper.updateByPrimaryKey(cmsStoreList);				
			if(upt==0){
				result.put("code",SysCode.error);
				message.append("提交失败,网络异常 ");
			}else{
				 //插入流程日志				
				int logcont = cmsStoreLogMapper.deleteByPrimaryKey(id);
				if(logcont==0){
					//回滚数据				
					result.put("code",SysCode.error);
					message.append("日志插入异常 ：库存已经回滚,删除出入库单失败,单号--"+id+"回滚操作"+MapUtil.getInt(data, "operate")+
							"数量："+editNumber);
				}
			}	
	    }	
		result.put("message", message.toString());			
		return result;
	}

	

	
	

	

	
	
	
   
    
  
}